<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <button onclick="setData()">设置缓存</button>
    <button onclick="getData()">读取缓存</button>
</body>
<script>
    // 如何实现可过期的 localStorage 数据?
    function setLocalStorage(key,value,time){
        const now = Date.now()
        const data = {
            value,
            dealTime: now + time
        }
        localStorage.setItem(key,JSON.stringify(data))
    }

    function getLocalStorage(key){
        const now = Date.now()
        const dataStr = localStorage.getItem(key)
        if(!dataStr){
            return null
        }
        const data = JSON.parse(dataStr)
        if (now > data.dealTime){
            console.error('数据过期已删除')
            localStorage.removeItem(key)
            return null
        }
        return data.value
    }
    function setData(){
        setLocalStorage('a','b',5000)
    }
    function getData(){
        console.log(getLocalStorage('a'))
    }
</script>
</html>